package com.carhailing.system.consumer;

import com.carhailing.common.domain.CouponUserMiddle;
import com.carhailing.system.service.CouponUserMiddleService;
import com.rabbitmq.client.Channel;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName CouponConsumer
 * @Description 描述
 * @Author junyi.wang
 * @Date 2024/8/4 14:37
 */
@Component
@Log4j2
public class CouponConsumer {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CouponUserMiddleService couponUserMiddleService;
    @RabbitListener(queuesToDeclare = @Queue("COUPON_USER"))
    private void CouponUserMiddle(Message message, CouponUserMiddle couponUserMiddle, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String messageId = message.getMessageProperties().getMessageId();
         Long count = redisTemplate.opsForSet().add("COUPON_USER_KEY", messageId);
        try {
         if(count==1) {
             couponUserMiddleService.save(couponUserMiddle);
             channel.basicAck(deliveryTag,false);
          }
         } catch (IOException e) {
            redisTemplate.opsForSet().remove("COUPON_USER_KEY",messageId);
            try {
                channel.basicReject(deliveryTag,false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
         }
       }
    }
